/**
 * Created by Administrator on 2017/3/13.
 */
var totalPrice=0.00;
$(function(){
    var NameMobile=JSON.parse(localStorage.getItem('NameMobile'))||'';
    var orderHtml=sessionStorage.getItem('orderHtml')||'';
    //加载购物车数据
    $.post(ajaxCar, function (res) {
        var data = JSON.parse(res);
        if (data.length == 0) {
            location.href=indexUrl;
        }
        var prices = 0, html = '',htmlDD = '',htmlSM='';
        for (var i = 0; i < data.length; i++) {
            prices += Number(data[i].num) * Number(data[i].oprice);
            if (data[i].deliverytype == 2) {
                htmlDD +='<div><img src=' + data[i].img + '><div>' +
                '<div class="lists_title">' + data[i].goodsname + '</div><div class="lists_detail"><span>￥' + data[i].price + '</span></div>'+
                '<div class="lists_num"><span><i class="iconal-zuyue"></i>' + data[i].item_endtime + '分钟</span></div></div></div></div>' +
                '<a class="weui-cell weui-cell_access" href="javascript:;">' +
                '<div class="weui-cell__bd weui-cell_primary"><p>门店地址: '+data[i].store.storename+'</p></div></a>' +
                '<a class="weui-cell weui-cell_access" href="javascript:;">' +
                '<div class="weui-cell__bd weui-cell_primary"><p>服务时间: '+data[i].starttime+'</p></div></a>' +
                '<a class="weui-cell weui-cell_access" href="javascript:;">' +
                '<div class="weui-cell__bd weui-cell_primary">' +
                '<p>服务技师: '+data[i].jishi.nickname+'</p></div></a></div>';
            } else if (data[i].deliverytype == 1) {
                htmlSM += '<div><img src=' + data[i].img + '><div>' +
                '<div class="lists_title">' + data[i].goodsname + '</div><div class="lists_detail"><span>￥' + data[i].price + '</span></div>'+
                '<div class="lists_num"><span><i class="iconal-zuyue"></i>' + data[i].item_endtime + '分钟</span></div></div></div></div>' +
                '<a class="weui-cell weui-cell_access" href="javascript:;">' +
                '<div class="weui-cell__bd weui-cell_primary"><p>服务地址: '+data[i].city+data[i].county+data[i].detailed_address+'</p></div></a>' +
                '<a class="weui-cell weui-cell_access" href="javascript:;">' +
                '<div class="weui-cell__bd weui-cell_primary"><p>服务时间: '+data[i].starttime+'</p></div></a>' +
                '<a class="weui-cell weui-cell_access" href="javascript:;">' +
                '<div class="weui-cell__bd weui-cell_primary">' +
                '<p>服务技师: '+data[i].jishi.nickname+'</p></div></a></div>';
            }
        }
        totalPrice=prices;
        htmlDD!=''&&(htmlDD='<a style="padding-left: 0" class="weui-cell weui-cell_access" href="javascript:;"><div class="weui-cell__bd weui-cell_primary">' +
        '<p class="DDorSMtitle"><i class="iconal-gongsi"></i>到店消费</p></div></a><div>'+htmlDD+'</div>');
        htmlSM!=''&&(htmlSM='<a style="padding-left: 0;margin-top: 5px" style="margin-top: 5px;" class="weui-cell weui-cell_access noTop" href="javascript:;"><div class="weui-cell__bd weui-cell_primary">' +
        '<p class="DDorSMtitle"><i class="iconal-locationfill"></i>上门服务</p></div></a><div>'+htmlSM+'</div>');
        html=htmlDD+htmlSM;
        $('.footer span').html('￥' + prices.toFixed(2));
        $('.lists').html(html);
        $.get(addressmoren, function (res) {
            var data = JSON.parse(res);
            if (data.id) {
                var a = $("a[class*='address']");
                for (var i = 0; i < a.length; i++) {
                    $(a[i]).attr('data-addressid',data.id).children('div').html('<p>' + data.cname + '  ' + data.tel + '</p><p>' + data.province + data.city + data.county + '</p><p>' + data.detailed_address + '</p>');
                }
            }
        });
        //加载可用优惠券
        $.get(
            couponajax,
            {
                'productprice':prices.toFixed(2)
            },
            function(res){
                var data=JSON.parse(res);
                if(res=='null'){
                 $('#formTJ_coupon').css('display','none');
                }else{
                    var html='';
                    for(var j in data){
                        html+='<li style="position:relative;">' +
                            '    <a data-name='+data[j].name+' onclick="chooseCoupon(this,'+data[j].id+','+data[j].cash+')" href="javascript:;" style="background-position:0 -10px;">' +
                            '        <p><span>￥ '+data[j].cash+'</span>元</p>' +
                            '        <p>'+data[j].name+'</p>' +
                            '        <p>截止时间：'+data[j].end_time+'</p>' +
                            '        <p></p>' +
                            '        <p>立即使用</p>' +
                            '    </a>' +
                            '</li>'
                    }
                    $('.list-cash-coupon').html(html);
                }
            }
        );
        //获取用户姓名电话
        if(NameMobile){
            $('input.name').val(NameMobile.name);
            $('input.mobile').val(NameMobile.mobile);
        }
    });
    //获取用户姓名电话
    if(NameMobile){
        $('input.name').val(NameMobile.name);
        $('input.mobile').val(NameMobile.mobile);
    }else{
        //ajax>>>>>>>>>>>>>>>>>>
    }
});

//返回选择项目
$('.back').click(function(){
    location.href=indexUrl;
});
//编辑按钮
$('.edit>a').click(function(){
    if($('.edit>a').html()=="编辑"){
        $('.edit>a').html('完成');
        $('.lists_num b').css('display','inline-block');
    }else{
        $('.edit>a').html('编辑');
        $('.lists_num b').css('display','none');
    }
});


///**编辑  数量加减**/
$('.lists_num .add').click(function(){
    $(this).prev('span').html($(this).prev('span').html()-0+1);
});
$('.lists_num .minus').click(function(){
    var minus=$(this).next('span');
    var self=this;
    if(parseInt(minus.html())==1){
        $.confirm("确定删除该商品?", function() {
            //点击确认后的回调函数
            $(self).parent().parent().parent().remove();
        }, function() {
            //点击取消后的回调函数
        });
    }else {
        minus.html(minus.html() - 0 - 1);
    }
});

// 弹出优惠券列表按钮
$('#formTJ_coupon').click(function(){
   $('.voucher-main').slideDown();
});
//优惠券选择
function chooseCoupon(self,id,price) {
    $('.voucher-main').slideUp();
    $('#formTJ_coupon').attr('data-id',id).find('p').html($(self).attr('data-name')+'  -'+price);
    var payPrice=totalPrice-price;
    $('.footer span').html('￥'+payPrice.toFixed(2));
}

//选择服务技师
function jishiCH(e){
    var choose=$(e).prev().prev().find('.weui-bar__item--on');
    if(choose.html()=='到店消费'&&$(e).prev().prev().find('.weui-tab__bd-item--active').find('p').html()=='请选择门店'){
        $.toast('请先选择门店','text');
        return false;
    }
    if($(e).prev().find('p').html()=='请选择服务时间'){
        $.toast('请先选择服务时间','text');
        setTimeout(function(){
            $(e).prev().click()
        },1000);
        return false;
    }
    if($('input.name').val()!=''||$('input.mobile').val()){
        var NameMobile={
            name:$('input.name').val(),
            mobile:$('input.mobile').val()
        };
        localStorage.setItem('NameMobile',JSON.stringify(NameMobile));
    }
    var dateTime=(new Date()).getFullYear()+'-'+$(e).prev().attr('data-day')+' '+$(e).prev().attr('data-startt');
    location.href=personnelUrl+'from=order&id='+$(e).parent().attr('data-id')+'&dateTime='+dateTime;
}

//立即支付按钮
function pay(self){
    if($('input.name').val()==''){
        $.toast('请输入姓名','cancel');
        return false;
    }
    if($('input.mobile').val()==''){
        $.toast('请收入手机号','cancel');
        return false;
    }
    if(!(/^1[34578]\d{9}$/.test($('input.mobile').val()))){
        $.toast('手机号填写有误','cancel');
        return false;
    }
    $.get(
        checkOrder,
        {
            couponid:$('#formTJ_coupon').attr('data-id'),
            nickN: $('input.name').val(),
            phone: $('input.mobile').val(),
            remark: $('input.remark').val()
        },
        function (res) {
            localStorage.setItem('NameMobile', JSON.stringify({
                name: $('input.name').val(),
                mobile: $('input.mobile').val()
            }));
            var data = JSON.parse(res);
            if (data.orderno) {
                var orderno = data.orderno;
                $.get(before_pay_check, {orderno: data.orderno}, function (res) {
                    var data = JSON.parse(res);
                    if (data.status == 0) {
                        var paytype = 'wechat';
                        $.post(paycash, {orderno: orderno, paytype: paytype}, function (m) {
                            if (!m.errno) {
                                m.data.timeStamp = String(m.data.timeStamp);
                                WeixinJSBridge.invoke('getBrandWCPayRequest', {
                                    'appId': m.data.appid ? m.data.appid : m.data.appId,
                                    'timeStamp': m.data.timeStamp,
                                    'nonceStr': m.data.nonceStr,
                                    'package': m.data.package,
                                    'signType': m.data.signType,
                                    'paySign': m.data.paySign
                                }, function (res) {
                                    $('.footer a').attr('data-orderno', orderno);
                                    if (res.err_msg == 'get_brand_wcpay_request:ok') {
                                        location.href = paycash + "&orderno=" + orderno + "&paytype=" + paytype + "&done=1";
                                    } else {
                                        $.toast("已取消支付", 'cancel');
                                        setTimeout(function () {
                                            location.href = orderUrl
                                        }, 1000);
                                    }
                                });
                            }
                        }, "json");
                    } else if (data.status == 1) {
                        $.toast('该项目预约时间已满，请重新下单', 'cancel');
                        setTimeout(function(){
                            location.href = indexUrl;
                        },2000);
                        return false;
                    }else{
                        $.toast(data.message, 'cancel');
                        setTimeout(function(){
                            location.href = indexUrl;
                        },2000);
                        return false;
                    }
                })
            }else{
                $.toast('预约失败，请重新下单', 'cancel');
                setTimeout(function(){
                    location.reload();
                },500);
                return false;
            }
    })
}



///**监听用户返回按钮**/
//var _system={
//    $:function(id){return document.getElementById(id);},
//    _client:function(){
//        return {w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight,bw:document.documentElement.clientWidth,bh:document.documentElement.clientHeight};
//    },
//    _scroll:function(){
//        return {x:document.documentElement.scrollLeft?document.documentElement.scrollLeft:document.body.scrollLeft,y:document.documentElement.scrollTop?document.documentElement.scrollTop:document.body.scrollTop};
//    },
//    _cover:function(show){
//        if(show){
//            this.$("cover").style.display="block";
//            this.$("cover").style.width=(this._client().bw>this._client().w?this._client().bw:this._client().w)+"px";
//            this.$("cover").style.height=(this._client().bh>this._client().h?this._client().bh:this._client().h)+"px";
//        }else{
//            this.$("cover").style.display="none";
//        }
//    },
//    _guide:function(click){
//        this._cover(true);
//        this.$("guide").style.display="block";
//        this.$("guide").style.top=(_system._scroll().y+5)+"px";
//        window.onresize=function(){_system._cover(true);_system.$("guide").style.top=(_system._scroll().y+5)+"px";};
//        if(click){_system.$("cover").onclick=function(){
//            _system._cover();
//            _system.$("guide").style.display="none";
//            _system.$("cover").onclick=null;
//            window.onresize=null;
//        };}
//    }
//}
//pushHistory();
//setTimeout(function () {
//    window.addEventListener("popstate", function(e) {
//        showBox("再按一次退出程序", 1000, function() {
//            pushHistory();
//        });
//    }, true);
//}, 1000);
//
//function pushHistory() {
//    var state = { title: "title", url: "#" };
//    window.history.pushState(state, "title", "#");
//}
//
//function showBox(msg, timeOut, onTimeOut) {
//    if (typeof timeOut === "undefined") timeOut = 2000;
//    setTimeout(function() {
//
//        if (typeof onTimeOut !== "undefined") {  onTimeOut();
//            tipsBox.createPayBox();
//        }
//    }, timeOut);
//}
//
//var tipsBox = {}
//tipsBox.container = '#tips-box';
//tipsBox.createPayBox = function() {
//    location.href=indexUrl;
//}
//tipsBox.hideTipsBox = function() { //关闭提提示框
//    $(tipsBox.container).hide();
//}
//tipsBox.tipsBoxCenter = function(_this) { //提示框居中
//    var windowHeight = $(window).height();
//    var _thisHeight = $(_this).css('height').replace('px','');
//    var top = parseFloat(windowHeight - _thisHeight) / 2;
//    $(_this).css('marginTop',top);
//}















